﻿using Framework.Core.Helper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Volo.Abp.Auditing;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Local;
using Volo.Abp.Uow;

namespace Framework.AuditLogging
{
	/// <summary>
	/// 审计日志持久化
	/// </summary>
	public class AuditingStore : IAuditingStore, ITransientDependency
	{
		public ILogger<AuditingStore> Logger { get; set; }
		protected IUnitOfWorkManager UnitOfWorkManager { get; }
		protected AbpAuditingOptions Options { get; }

		private readonly ILocalEventBus _localEventBus;

		public AuditingStore(
		   IUnitOfWorkManager unitOfWorkManager,
		   IOptions<AbpAuditingOptions> options, 
		   ILocalEventBus localEventBus)
		{
			UnitOfWorkManager = unitOfWorkManager;
			Options = options.Value;
			_localEventBus = localEventBus;
			Logger = NullLogger<AuditingStore>.Instance;
		}

		/// <summary>
		/// 保存审计日志
		/// </summary>
		/// <param name="auditInfo"></param>
		/// <returns></returns>
		public virtual async Task SaveAsync(AuditLogInfo auditInfo)
		{
			if (!Options.HideErrors)
			{
				await SaveLogAsync(auditInfo);
				return;
			}

			try
			{
				await SaveLogAsync(auditInfo);
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Could not save the audit log object: " + Environment.NewLine + auditInfo.ToString());
				Logger.LogException(ex, LogLevel.Error);
			}
		}

		protected virtual async Task SaveLogAsync(AuditLogInfo auditInfo)
		{
			await _localEventBus.PublishAsync(auditInfo);
			//Logger.LogDebug("请求追踪:" + JsonHelper.ObjToStr(auditInfo, "yyyy-MM-dd HH:mm:ss"));
		}
	}
}
